package com.sugar.service.system;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Component;

import com.sugar.base.core.HibernateTemplateSupport;
import com.sugar.domain.system.privilege.PrivilegeResourceItem;
import com.sugar.domain.system.privilege.PrivilegeResourceModel;


@Component
public class InitSystemTreeMenuService extends HibernateTemplateSupport{
	
	private Log log = LogFactory.getLog(getClass()) ;

	//static String str = "D:/Workspaces/MyEclipse8.5/Project/sugar/WebRoot/xml_tree/tree7.xml" ;
	//static String str1 = "D:/Workspaces/MyEclipse8.5/Project/sugar/WebRoot/xml_tree/funcbar7.xml" ;
	
	private String path = null ;
	
	/**
	 * 初始化所以的权限资源菜单
	 * @param request
	 */
	public void initMenu(HttpServletRequest request) {
		log.info("[....Log4j]：系统初始化，首次运行，加载所以的权限资源并持久化") ;
		
		SessionFactory sf = this.getHibernateTemplate().getSessionFactory() ;
		Session session = sf.openSession() ;
		session.beginTransaction().begin() ;
		
		path = request.getSession().getServletContext().getRealPath("/xml_tree") ;
		System.out.println(path);
		treeMenuRootXML(path,session) ;
		
		session.beginTransaction().commit() ;
		
		session.close() ;
		sf.close() ;
	}
	
	/**
	 * 加载所以的tree和funbar菜单
	 * @param session 进行持久化
	 */
	public void treeMenuRootXML(String path,Session session) {
		try {
			File file = new File(path) ;
			for(int i=1;i <=7; i++) {
				log.info("[....Log4j]：正在加载"+file.getAbsoluteFile()+"\\tree"+i+".xml") ;
				
				SAXBuilder sb = new SAXBuilder() ;
				Document docTree = sb.build(new File(file.getAbsoluteFile()+"\\tree"+i+".xml")) ;
				Element docTreeRoot = docTree.getRootElement() ;
				
				Document docBar = sb.build(new File(file.getAbsoluteFile()+"\\funcbar"+i+".xml")) ;
				Element docBarRoot = docBar.getRootElement() ;
				
				PrivilegeResourceModel model = new PrivilegeResourceModel() ;
				model.setM_name(docTreeRoot.getAttributeValue("text")) ;
				model.setM_desc("无描述") ;
				
				session.save(model) ;
				
				parseTreeMenuXML(docTreeRoot,docBarRoot,model,null,session) ;
				}
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 加载tree.xml
	 * @param element tree根元素
	 * @param funcbarElt menubar元素
	 * @param model 资源模块
	 * @param item 资源列表
	 * @param session 数据库会话
	 */
	@SuppressWarnings("unchecked")
	public void parseTreeMenuXML(Element element,Element funcbarElt,PrivilegeResourceModel model,PrivilegeResourceItem item,Session session) {
		
		List<?> childs = element.getChildren() ;
		
		if(null != childs && childs.size() > 0) {
			for(int i=0; i<childs.size(); i++) {
				Element elt = (Element) childs.get(i) ;
				
				if(elt.getAttributeValue("text") != null) {
					//System.out.println(elt.getAttributeValue("text") + "=" + elt.getAttributeValue("parent") + "=" + elt.getAttributeValue("child"));
					
					PrivilegeResourceItem resource = new PrivilegeResourceItem() ;
					resource.setMc_name(elt.getAttributeValue("text")) ;
					resource.setParent(item) ;
					resource.setMlist(model) ;
					
					if(elt.getChildText("userdata") != null) {
						resource.setMc_url(elt.getChildText("userdata")) ;
						//System.out.println("\t"+elt.getChildText("userdata")); System.out.println("");
					}
					
					session.save(resource) ;
					
					//加载funcbar.xml
					if(null != elt.getAttributeValue("id") && !"item_root".equals(elt.getAttributeValue("id"))) {
						parseTreeFuncBarXML(elt.getAttributeValue("id"), funcbarElt, model, resource, session) ;
					}
					
					List<Element> childrens = elt.getChildren() ;
					
					if(null != childrens && childrens.size() > 0) {
						parseTreeMenuXML(elt,funcbarElt,model,resource,session) ;
					}
				}
			}
		}
	}
	
	/**
	 * 加载解析funbar.xml
	 * @param element
	 * @param funcbarElt
	 * @param model
	 * @param item
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	public void parseTreeFuncBarXML(String element,Element funcbarElt,PrivilegeResourceModel model,PrivilegeResourceItem item,Session session) {
		
		Element el = funcbarElt.getChild(element) ;
		
		if(null != el) {
			
			List<Element> barList = el.getChildren() ;
		
			for(int i=0; i<barList.size(); i++) {
				Element bar = barList.get(i) ;
				PrivilegeResourceItem barlist = new PrivilegeResourceItem() ;
				barlist.setMc_name(bar.getAttributeValue("text")) ;
				barlist.setMc_url(bar.getText()) ;
				barlist.setMc_desc("无描述") ;
				barlist.setParent(item) ;
				barlist.setMlist(model) ;
				
				session.save(barlist) ;
				//System.out.println(bar.getAttributeValue("text") + "--" + bar.getText());
			}
		}
	}
	
	/*public static void main(String[] args) {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("app*.xml") ;
	
	InitSystemTreeMenuService is = (InitSystemTreeMenuService) ctx.getBean("initSystemTreeMenuService") ;
	
	is.initMenu(null) ;
	}*/
	
}
